//
//  ChartCell.swift
//  HuaYun
//
//  Created by enghou on 2018/12/12.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit
import Charts
class ChartCell: UITableViewCell {
    
    var _source: [JSON] = []
    var source: [JSON] {
        set{
            if _source != newValue {
                _source = newValue
                drawdata()
            }
        }
        get{
            return _source
        }
    }
    private var segcontrol: AccompanySegmentControl = AccompanySegmentControl.init(items: ["人员数量","人工成本"])
    @IBOutlet weak var pieChartView: PieChartView!
    @IBOutlet private weak var expireBackLabel: UILabel!
    @IBOutlet private weak var allThePeopleLabel: UILabel!
    @IBOutlet private weak var laborPutLabel: UILabel!
    @IBOutlet private weak var peopleOutLabel: UILabel!
    @IBOutlet private weak var laborOutLabel: UILabel!
    @IBOutlet private weak var directLabel: UILabel!
    @objc func drawdata()->Void{
        var datas: [(String,Double)] = []
        switch segcontrol.selectedSegmentIndex {
        case 0:
            datas = source.map({ (json) -> (String,Double) in
                return (json.contents?["typeName"]?.rawString() ?? "",json.contents?["personAmount"]?.double ?? 0.0)
            })
            pieChartView.centerText = "总人数:\n" + String(datas.reduce(0, { (result, element) -> Int in
                return result + Int(element.1)
            }))
            let marker = pieChartView.marker as! PieMarker
            marker.currentidx = 0
            break
        default:
            datas = source.map({ (json) -> (String,Double) in
                return (json.contents?["typeName"]?.rawString() ?? "",json.contents?["totalAmount"]?.double ?? 0.0)
            })
            pieChartView.centerText = "总成本:\n" + String(datas.reduce(0, { (result, element) -> Int in
                return result + Int(element.1)
            }) / 1000000).rmbformat + "万"
            let marker = pieChartView.marker as! PieMarker
            marker.currentidx = 1
            break
        }
        
        let sorted = datas.sorted(by: {$0.1 > $1.1})
        if sorted.first?.1 == 0 {
            pieChartView.data = nil
            pieChartView.animate(xAxisDuration: TimeInterval.init(0.25), yAxisDuration: TimeInterval.init(0.25), easing: nil)
            return
        }
        let yvals = datas.map { (name,value) -> PieChartDataEntry in
            return PieChartDataEntry.init(value: value, label: name)
        }
        let dataset = PieChartDataSet.init(values: yvals, label: nil)
        dataset.selectionShift = 2
        dataset.colors = [UIColor.hex("7B3EDD"),UIColor.hex("2C3975"),UIColor.hex("E9C42B"),UIColor.hex("29BABF"),UIColor.hex("39BD60"),UIColor.hex("2785FF")]
        dataset.drawValuesEnabled = false
        let data = PieChartData.init(dataSets: [dataset])
        pieChartView.drawSlicesUnderHoleEnabled = true
        data.setValueFont(UIFont.systemFont(ofSize: 10.0))
        data.setValueTextColor(UIColor.lightGray)
        pieChartView.data = data
        pieChartView.animate(xAxisDuration: TimeInterval.init(0.25), yAxisDuration: TimeInterval.init(0.25), easing: nil)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentView.addSubview(segcontrol)
        segcontrol.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(30)
        }
        segcontrol.addTarget(self, action: #selector(drawdata), for: UIControl.Event.valueChanged)
        segcontrol.selectedSegmentIndex = 0
        segcontrol.view.backgroundColor = UIColor.init(red: 36 / 255, green: 115 / 255, blue: 215 / 255, alpha: 1)
        segcontrol.tintColor = UIColor.white
        segcontrol.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.init(red: 36 / 255, green: 115 / 255, blue: 215 / 255, alpha: 1),NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], for: .selected)
        segcontrol.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.hex("999999"),NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], for: .normal)
        config(pie: pieChartView, width: 0)
    }
    
    func config(pie: PieChartView, width type: Int)->Void{
        pie.chartDescription = nil
        pie.setExtraOffsets(left: 0, top: 20, right: 0, bottom: 20)
        pie.usePercentValuesEnabled = false  //转化为百分比
        pie.drawEntryLabelsEnabled = false //显示区块文本
        pie.entryLabelFont = UIFont.systemFont(ofSize: 10) //区块文本的字体
        pie.entryLabelColor = UIColor.white
        pie.drawSlicesUnderHoleEnabled = false
        pie.noDataText = "暂无数据"
        pie.drawHoleEnabled = true  //这个饼是空心的
        pie.holeRadiusPercent = 0.5  //空心半径黄金比例
        pie.holeColor = UIColor.white //空心颜色设置为白色
        pie.transparentCircleRadiusPercent = 0.25  //半透明空心半径
        pie.drawCenterTextEnabled = true
        pie.legend.enabled = true
        pie.legend.drawInside = true
        pie.legend.form = .circle //图示：原、方、线
        pie.legend.formSize = 8 //图示大小
        pie.legend.formToTextSpace = 5 //文本间隔
        pie.legend.font = UIFont.systemFont(ofSize: 14)
        pie.legend.textColor = UIColor.gray
        pie.legend.horizontalAlignment = .center
        pie.legend.verticalAlignment = .bottom
        pie.drawMarkers = true
        let marker = PieMarker(color: UIColor(white: 0, alpha: 0.7), font: .systemFont(ofSize: 12), textColor: .white, insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
        marker.currentidx = type
        pie.marker = marker
        marker.chartView = pie
        pie.animate(xAxisDuration: 1.0, yAxisDuration: 1.0, easingOption: .easeInBack)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }
    
}
